import axios from 'axios'
import Vue from 'vue'
import Router from './router'

const http = axios.create({
  baseURL: 'http://localhost:3000/web/api'
})

http.interceptors.request.use(
  function(config) {
    if (localStorage.token) {
      config.headers.Authorization = 'Bearer ' + localStorage.token
    }
    return config
  },
  function(err) {
    return Promise.reject(err)
  }
)

http.interceptors.response.use(
  res => {
    return res
  },
  err => {
    const errMessage = err.response.data.message
    if (errMessage) {
      Vue.prototype.$notify(errMessage)
    }
    if (err.response.status === 401) {
      Router.push('/login')
    }
    return Promise.reject(err)
  }
)

export default http
